/* eslint-disable no-unused-vars */
/* eslint-disable react/jsx-no-bind */
import React, { useEffect, useState } from 'react'
import { Modal, Image, Tag, message, Tooltip } from 'antd'
import { getGamesInfo } from '../../../../../utils/service'
import { GameContainer } from './style'
import { heroList } from '../hero_list'
import {
  FILTER_HERO_NAME,
  FILTERCURRENTDATA,
  TEAM_FILTER_DATA,
  UPDATE_CURRENT_PLAYER_KD,
  GET_EQUIP_IMG,
  getspellImgUrl
} from './contants'
import { FILTER_KDA } from '../../contants'

const hrStyle: React.CSSProperties = {
  display: 'block',
  border: '2px solid #f0f0f0',
  margin: '10px'
}

const itemLine: React.CSSProperties = {
  margin: '10px',
  display: 'flex',
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'space-between'
}

const itemPic: React.CSSProperties = {
  width: '40px',
  height: '40px',
  marginRight: '10px'
}

const itemEquip: React.CSSProperties = {
  width: '34px',
  height: '34px',
  marginRight: '2px'
}

const equipContainer: React.CSSProperties = {
  minWidth: '260px',
  maxWidth: '260px',
  display: 'flex',
  justifyContent: 'center'
}

const spellContainer: React.CSSProperties = {
  display: 'flex',
  justifyContent: 'center'
}

const itemName: React.CSSProperties = {
  minWidth: '180px',
  maxWidth: '180px',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
  textAlign: 'center'
}

const itemDefault: React.CSSProperties = {
  minWidth: '160px',
  maxWidth: '160px',
  paddingRight: '20px',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
  textAlign: 'center'
}

interface IGameInfoProps {
  isModalOpen: boolean
  handleModalOpen: () => void
  record: object
}

interface PlayerData {
  participantId: number
}
interface StatusData {
  participantId: number
}

const GameInfo: React.FC<IGameInfoProps> = props => {
  const [teamOne, setTeamOne]: any = useState([])
  const [teamTwo, setTeamTwo]: any = useState([])

  const getGameData = async (record: any) => {
    const res = await getGamesInfo({
      gameId: record.gameId
    })
    // 截取本局游戏的英雄图标以及英雄名称
    let team_one_list = res.data.participants.splice(0, 5)
    let team_two_list = res.data.participants

    let updatedTeamOne = [...teamOne]
    let updatedTeamTwo = [...teamTwo]
    team_one_list.map((item: any) => {
      const hero = FILTER_HERO_NAME(item.championId, heroList)
      updatedTeamOne = [...updatedTeamOne, hero]
    })
    team_two_list.map((item: any) => {
      const hero = FILTER_HERO_NAME(item.championId, heroList)
      updatedTeamTwo = [...updatedTeamTwo, hero]
    })

    setTeamOne(updatedTeamOne)
    setTeamTwo(updatedTeamTwo)

    // 存储当前对局*位英雄信息
    const teamList = [...team_one_list, ...team_two_list]

    await localStorage.setItem(
      'currentMatchData',
      JSON.stringify(await FILTERCURRENTDATA(res.data.participantIdentities, teamList))
    )
    // 存储单局玩家的匹配数据
    await localStorage.setItem('currentMatchData-player', JSON.stringify(await getCurrentData_Player()))

    await TEAM_FILTER_DATA(
      team_one_list,
      team_two_list,
      JSON.parse(localStorage.getItem('currentMatchData-player')!).playerTeamOneData,
      JSON.parse(localStorage.getItem('currentMatchData-player')!).playerTeamTwoData
    )

    try {
      await Promise.all([
        UPDATE_CURRENT_PLAYER_KD(updatedTeamOne, team_one_list),
        UPDATE_CURRENT_PLAYER_KD(updatedTeamTwo, team_two_list)
      ])
    } catch (error) {
      message.error('获取对局信息失败')
    }
  }

  // 存储单局玩家数据
  const getCurrentData_Player = async () => {
    const current_data = await JSON.parse(localStorage.getItem('currentMatchData')!)
    const [team_one_list, team_two_list, status_one_list, status_two_list] = [
      current_data.playerInfo.splice(0, 5),
      current_data.playerInfo,
      current_data.statusInfo.splice(0, 5),
      current_data.statusInfo
    ]
    const playerTeamOneData: Array<object> = team_one_list
      .map((playerData: PlayerData) => {
        const statusData = status_one_list.find(
          (status: StatusData) => status.participantId === playerData.participantId
        )
        return statusData ? [playerData, statusData] : null
      })
      .filter((data: Array<object>) => data !== null)
    const playerTeamTwoData = team_two_list
      .map((playerData: PlayerData) => {
        const statusData = status_two_list.find(
          (status: StatusData) => status.participantId === playerData.participantId
        )
        return statusData ? [playerData, statusData] : null
      })
      .filter((data: Array<object>) => data !== null)
    if (!playerTeamOneData.length) {
      playerTeamOneData.push({ status: 'TEAM ONE NULL' })
    }
    if (!playerTeamTwoData.length) {
      playerTeamTwoData.push({ status: 'TEAM TWO NULL' })
    }
    return {
      playerTeamOneData: [...playerTeamOneData],
      playerTeamTwoData: [...playerTeamTwoData]
    }
  }

  const _init = () => {
    setTeamOne([])
    setTeamTwo([])
  }

  const handleOk = () => {
    _init()
    props.handleModalOpen()
  }

  const handleCancel = () => {
    _init()
    props.handleModalOpen()
  }

  useEffect(() => {
    if (props.isModalOpen) {
      getGameData(props.record)
    }
  }, [props.isModalOpen])

  return (
    <Modal
      width={1200}
      title="对局预览"
      okText="确定"
      cancelText="关闭"
      destroyOnClose={true}
      keyboard={false}
      maskClosable={false}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <hr style={hrStyle} />
      <GameContainer>
        {teamOne.map((item: any, index: number) => {
          return (
            <div key={index} style={itemLine}>
              <Image preview={false} style={itemPic} src={item.pic} />
              <div style={itemName}>{item.name}</div>
              <Tooltip placement="right" title={item.player.summonerName + ' #' + (item.player.tagLine || 'None')}>
                <div style={itemDefault} className="kda">
                  {item.player.summonerName} ({item.player.summonerName + ' #' + (item.player.tagLine || 'None')})
                </div>
              </Tooltip>
              <div style={itemDefault} className="kda">
                {item.stats.kills} / {item.stats.deaths} / {item.stats.assists}
              </div>
              <div style={equipContainer}>
                {GET_EQUIP_IMG(
                  item.stats.item0,
                  item.stats.item1,
                  item.stats.item2,
                  item.stats.item3,
                  item.stats.item4,
                  item.stats.item5
                ).map((item: any, index: number) => {
                  return (
                    <div key={index}>
                      <Image preview={false} style={itemEquip} src={item} />
                    </div>
                  )
                })}
              </div>
              {/* 召唤师技能 */}
              <div style={spellContainer}>
                {item.spellList.map((item: any, index: number) => {
                  return (
                    <div key={index}>
                      <Image preview={false} style={itemEquip} src={getspellImgUrl(item)} />
                    </div>
                  )
                })}
              </div>
              <div style={itemDefault}>
                <Tag
                  color={
                    FILTER_KDA(item) === '汗血宝马'
                      ? 'blue'
                      : FILTER_KDA(item) === '上等马'
                      ? 'steelblue'
                      : FILTER_KDA(item) === '中等马'
                      ? 'yellow'
                      : FILTER_KDA(item) === '下等马'
                      ? 'orange'
                      : FILTER_KDA(item) === '牛马'
                      ? 'red'
                      : FILTER_KDA(item) === '马粪'
                      ? 'grey'
                      : FILTER_KDA(item) === '没马'
                      ? 'black'
                      : ''
                  }
                >
                  {FILTER_KDA(item)}
                </Tag>
              </div>
            </div>
          )
        })}
        <hr style={hrStyle} />
        {teamTwo.map((item: any, index: number) => {
          return (
            <div key={index} style={itemLine}>
              <Image preview={false} style={itemPic} src={item.pic} />
              <div style={itemName}>{item.name}</div>
              <Tooltip placement="right" title={item.player.summonerName + ' #' + (item.player.tagLine || 'None')}>
                <div style={itemDefault} className="kda">
                  {item.player.summonerName} ({item.player.summonerName + ' #' + (item.player.tagLine || 'None')})
                </div>
              </Tooltip>
              <div style={itemDefault} className="kda">
                {item.stats.kills} / {item.stats.deaths} / {item.stats.assists}
              </div>
              <div style={equipContainer}>
                {GET_EQUIP_IMG(
                  item.stats.item0,
                  item.stats.item1,
                  item.stats.item2,
                  item.stats.item3,
                  item.stats.item4,
                  item.stats.item5
                ).map((item: any, index: number) => {
                  return (
                    <div key={index}>
                      <Image preview={false} style={itemEquip} src={item} />
                    </div>
                  )
                })}
              </div>
              {/* 召唤师技能 */}
              <div style={spellContainer}>
                {item.spellList.map((item: any, index: number) => {
                  return (
                    <div key={index}>
                      <Image preview={false} style={itemEquip} src={getspellImgUrl(item)} />
                    </div>
                  )
                })}
              </div>
              <div style={itemDefault}>
                <Tag
                  color={
                    FILTER_KDA(item) === '汗血宝马'
                      ? 'blue'
                      : FILTER_KDA(item) === '上等马'
                      ? 'steelblue'
                      : FILTER_KDA(item) === '中等马'
                      ? 'yellow'
                      : FILTER_KDA(item) === '下等马'
                      ? 'orange'
                      : FILTER_KDA(item) === '牛马'
                      ? 'red'
                      : FILTER_KDA(item) === '马粪'
                      ? 'grey'
                      : FILTER_KDA(item) === '没马'
                      ? 'black'
                      : ''
                  }
                >
                  {FILTER_KDA(item)}
                </Tag>
              </div>
            </div>
          )
        })}
      </GameContainer>
      <hr style={hrStyle} />
    </Modal>
  )
}

export default GameInfo
